package com.cloud.wenxi.controller;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.wenxi.service.BalancerService;
import com.ultrapower.springcloud.domain.CommonResult;
import com.ultrapower.springcloud.domain.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther shiwenxi
 * @date 2022-10-20
 */
@RestController

public class CircleBreakerController {

    @Value("${service-url.nacos-user-service}")
    public String SERVICE_URL;


//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private BalancerService balancerService;


    /**
     * @param id
     * @return
     */
    @GetMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback",fallback = "handlerFallback")//没有配置对应的fallback
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "handlerFallback")
    public CommonResult<?> fallback(@PathVariable("id") Long id) {
//        restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        CommonResult<?> forObject = balancerService.paymentSQL(id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        } else if (forObject.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应的记录,空指针异常");
        }
        return forObject;
    }

    //自定义fallback
    public CommonResult<?> handlerFallback(@PathVariable("id") Long id,Throwable throwable){
        return new CommonResult<>(444,"兜底异常handlerFallback"+throwable.getMessage(),new Payment(id.intValue(), null));
    }


    @GetMapping("/consumer/paymentSQL/{id}")
    public CommonResult<?> payment(@PathVariable("id") Long id){
        return balancerService.paymentSQL(id);
    }


    //自定义blockHandler
    public CommonResult<?> blockHandler(@PathVariable Long id, BlockException e){
        return new CommonResult<>(444,"blockHandler-sentinel限流,无此流水号:blockException:"+e.getMessage(),new Payment(id.intValue(), null));
    }

}
